const jwt = require('jsonwebtoken')
const { secret_code } = require('../utils/index')
module.exports = () => {
  return async (ctx, next) => {
    const whiteList = ['/users/login', '/users/register']
    console.log('auth中间件:', whiteList.includes(ctx.path))
    if (!whiteList.includes(ctx.path)) {
      // console.log(ctx.request.headers, 'ctx.request.headers------------->')
      const { authorization } = ctx.request.headers
      console.log('authorization:', authorization)
      try {
        const token = jwt.verify(authorization, secret_code)
        console.log('token:', JSON.stringify(token))
        // 全局的中间件 可以帮助我们开发可复用的中间件函数，比如登陆校验token中间件
        // 通过校验之后往下走
        await next()
      } catch (err) {
        // 没有通过
        ctx.body = { code: -1, msg: err }
      }
    } else {
      // 继续往下走
      await next()
    }
  }
}
